package com.lyn.android_lyn_serialport;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.lyn.serialPort.BytesAndHex;
import com.lyn.serialPort.Device;
import com.lyn.serialPort.SerialPortFinder;
import com.lyn.serialPort.SerialPortManager;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private SerialPortManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SerialPortFinder finder = new SerialPortFinder();
        Device device = finder.getDevice("ttyS1");
        if (device == null) return;
        manager = new SerialPortManager();
        boolean openSerialPort = manager.openSerialPort(device.getName(), 9600);
        Log.i("serialPort","串口打开状态:"+openSerialPort);

    }


    public void send(View view) {
        if (manager==null){
            Log.i("long","manager==null");
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String content=strTo16("测试消息123AB");
                Log.i("long","测试消息:"+content);
                String cmd="AT*MSGS=13307068245,3,"+content.length()+","+content;
                byte[] bytes = manager.sendData(cmd.getBytes(), 10000);
                String bytesToHex = BytesAndHex.bytesToHex(bytes);
                Log.i("long",bytesToHex);
            }
        }).start();

    }

    /**
     * 字符串转化成为16进制字符串
     * @param s
     * @return
     */
    public static String strTo16(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            int length= 4-s4.length();
            if (length>0){
                for (int j = 0; j < length; j++) {
                    s4="0"+s4;
                }
            }
            Log.i("long","单个hex字符串:"+s4);
            str = str + s4;
        }
        return str;
    }


}